<?php

namespace App\Http\Controllers\v1;



// 引入鉴权类
use App\Http\commen\Common;
use App\Model\CardModel;
use App\Model\FeedbackModel;
use App\Model\SchoolModel;
use Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

/**
 * 文件上传
 * Class QiniuController
 * @package App\Http\Controllers\v1
 */
class QiniuController extends BaseController
{

    /**
     * 保存发帖图片
     * @param Request $request
     * @return QiniuController
     * @throws \Exception
     */
    public function AddSendPasteImage(Request $request){
        $token = $request ->header('token');
        $uuid = Cache::get($token)['uuid'];//
        $card_id = $request ->get('card_id');//card id
        $cid = $request ->get('cid');//分类id

        if(empty($card_id) || empty($cid)){
            return $this->error('缺少参数!');
        }

        $file = $request ->file('file');

        //上传图片
        $image_adar =   $this -> image_upload($file);

        if(empty($image_adar)){
            return $this->error('图片上传失败！');
        }

        $res = (new CardModel()) -> AddSendPasteImage($uuid,$cid,$card_id,$image_adar);//只有内容

        if($res['code']){
            return $this->success('上传成功',$res['data']);
        }else{
            return $this->error('上传失败！',$res['data']);
        }

    }

    /**
     * 发帖
     * @param Request $request
     * @return QiniuController
     */
    public function AddSendPaste(Request $request){
        $token = $request ->header('token');
        $uuid = Cache::get($token)['uuid'];//

        $uNmae = $request ->get('uNmae');//发帖人名称
        $uhead_img= $request ->get('head_img');//发帖人头像
        $sid= $request ->get('sid');//学校id
        $school_name = $request ->get('SchoolName');//学校名称
        $content = $request ->get('content');//发帖内容
        $cName = $request ->get('cName');//话题分类
        $cid = $request ->get('cid');//话题分类id
        $sex = $request ->get('sex');//性别
        $is_anonymity = $request ->get('is_anonymity');//是否匿名
//        $file = $request ->file('file');//图片

    if(
           empty($uNmae)
        || empty($uhead_img)
        || empty($sid)
        || empty($school_name)
        || empty($content)
        || empty($cName)
        || is_null($is_anonymity)
        || empty($cid)
        || is_null($sex)
    ){
        return $this->error('缺少参数！');
    }

        $res = (new CardModel()) -> AddSendPasteContent($uuid,$uNmae,$uhead_img,$sid,$school_name,$content,$is_anonymity,$cid,$sex);//只有内容

        if($res['code']){
            return $this->success('上传成功',$res['data']);
        }else{
            return $this->error('上传失败！',$res['data']);
        }

    }

    /**
     * 学校添加
     * @param Request $request
     * @return QiniuController
     * @throws \Exception
     */
    public function AddSchool(Request $request){
        $token = $request ->header('token');
        $uuid = Cache::get($token)['uuid'];

        $school_name = $request ->get('name');//学校名称
        $file = $request ->get('image');//学校图片
        $address = $request ->get('address');//学校地址

        if(empty($school_name) || empty($file) || empty($address)){
            return $this->error('缺少参数！');
        }

        $res = (new SchoolModel()) -> AddSchool($uuid,$school_name,$address,$file);//只有内容

        if($res['code']){
            return $this->success('上传成功',$res['data']);
        }else{
            return $this->error('上传失败！',$res['data']);
        }


    }

    /**
     * 软件吐槽
     * @param Request $request
     * @return QiniuController
     * @throws \Exception
     */
    public function suggest(Request $request){
        $token = $request ->header('token');
        $uuid = Cache::get($token)['uuid'];
        $image = $request ->get('image');

        $content  = $request ->get('content');//内容
        if(empty($content)){
            return $this->error('缺少参数！');
        }

            $res = (new FeedbackModel()) -> suggestContent($uuid,$content,$image);//只有内容

            if($res['code']){
                return $this->success('上传成功');
            }else{
                return $this->error('上传失败！');
            }



    }

    /**
     * 软件吐槽 保存图片
     * @param Request $request
     * @return QiniuController
     * @throws \Exception
     */
    public function suggestImage(Request $request){

        $file  = $request ->get('file');//内容

        if(is_null($file)){
            return $this->error('请上传图片');
        }

        //上传图片
        $image_adar =   $this -> image_upload($file);

        if(empty($image_adar)){
            return $this->error('图片上传失败！');
        }

        if(!empty($image_adar)){
            return $this->success('上传成功',$image_adar);
        }else{
            return $this->error('上传失败！','上传失败！');
        }

    }

    /**
     * 图片验证上传
     * @param Request $request
     * @return array 图片地址
     * @throws \Exception
     */
    public function store(Request $request) {

        try {
            $file = $request -> file('file');
        } catch (\Exception $e) {
            return $this->error($e ->getMessage());
        }
        // 没有文件
        if(is_null($file)){
            $this->error('请上传文件');
        }

        $ext = $file->getClientOriginalExtension();//获取文件的后缀名
        $path = $file->getRealPath();//获取文件的 绝对路径
        $size = $file -> getSize();//得到文件大小

        //判断文件大小
        if(Common::ByteSize($size) > 2048 ){
            $this->error('超出最大文件上传');
        }

        $data = array('png','jpg','gif','bmp','jpeg','gif');
        if(!in_array($ext,$data)){
            return $this->error('不合法的文件');
        }

        // 文件名称
        $name = 'image/'.Date("Y/m/d").'/'.str_random(32).'.'.$ext;

          $res =  $this->qiniu_upload($name,$path);

          if($res['code']){
              return $this->success('上传成功',$res['data']);
          }else{
              return $this->error('上传失败！',$res['data']);

          }

    }

    /**
     * 图片上传
     * @param $file
     * @return QiniuController
     * @throws \Exception
     */
    public function image_upload($file){


        $ext = $file->getClientOriginalExtension();//获取文件的后缀名
        $path = $file->getRealPath();//获取文件的 绝对路径
        $size = $file -> getSize();//得到文件大小

        //判断文件大小
        if(Common::ByteSize($size) > 2048 ){
            $this->error('超出最大文件上传');
        }

        $data = array('png','jpg','gif','bmp','jpeg','gif');
        if(!in_array($ext,$data)){
            return $this->error('不合法的文件');
        }

        // 文件名称
        $name = 'image/'.Date("Y/m/d").'/'.str_random(32).'.'.$ext;

        $res =   $this->qiniu_upload($name,$path);

        if($res['code']){
            return $res['data'];
        }else{
            return null;

        }
    }

    /**
     * 七牛云 基础 操作
     * @param $name 文件名称
     * @param $filePath 上传路径
     * @return array
     * @throws \Exception
     */
    function qiniu_upload($name,$filePath) {

// 需要填写你的 Access Key 和 Secret Key
        $accessKey = env('AK');
        $secretKey = env('SK');
        $bucket = env('bucket');

// 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);

// 生成上传 Token
        $token = $auth->uploadToken($bucket);


        $uploadMgr = new UploadManager();

// 调用 UploadManager 的 putFile 方法进行文件的上传。
        try {
        $uploadMgr->putFile($token, $name, $filePath);

        } catch (\Exception $e) {
            return ['code' =>false,'data' => $e ->getMessage()];
        }

        return ['code' =>true,'data' => 'https://image.zoba.fun/' . $name];

//删除本地图片
//        unlink($filePath);
    }
}
